<style lang="less">
    @import './select-keyword-cover.css';
</style>

<template>
    <div>
        <Card :bordered="false">
            <p slot="title">数据总数：{{total_data_num}} 重复：{{chongfu_num}} 覆盖率：{{fugailv}} 平台：{{pingtai_num}} 异常：{{yichang_num}}</p>
            <div :class="input_data_div_display">

                <div>
                    <p class="zhu-text">
                        <span class="font-color-red padding-top-5 padding-down-5 text-bold">(注：您的数量为普通100条/精准10条！并不支持多条匹配！) </span>
                        <span> 请输入关键词（一行一个） 例如：合众康桥</span>
                    </p>
                </div>

                <div class="editor-div">
                    <editor v-model="editor_content" @init="initEditor" lang="html" theme="chrome" height="400"></editor>
                </div>

                <Row class="padding-top-5">
                    <Col span="8">
                        <div>选项设置：</div>
                        <div>
                            <RadioGroup v-model="optionSettings" vertical>
                                <Radio label="putong">
                                    <span>普通模式：获取搜索结果内容</span>
                                </Radio>
                                <Radio label="jingzhun">
                                    <span>精准模式：获取搜索结果内容以及详细内容</span>
                                </Radio>
                            </RadioGroup>
                        </div>
                    </Col>
                    <Col span="8">
                        <div>搜索引擎选择：</div>
                        <div>
                            <Select v-model="searchEngineModel" multiple style="width:260px">
                                <Option v-for="item in searchEngineList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                            </Select>
                        </div>
                    </Col>
                    <Col span="8">
                        <div>排名选择：</div>
                        <div>
                            <Select v-model="rankModel" style="width:200px">
                                <Option v-for="item in rankList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                            </Select>
                        </div>
                    </Col>
                </Row>

                <Row>
                    <Col span="2" class="height-32px">覆盖条件：</Col>
                    <Col span="10">
                        <Row><Input v-model="fugai_tiaojian"></Input></Row>
                        <Row>
                            <div class="font-color-red padding-top-5 padding-down-5">(空为匹配所有)请输入或选择要匹配的条件关键词，多添加使用符号 或: "|"</div>
                        </Row>
                    </Col>
                </Row>

                <Row>
                    <Button type="success" icon="ios-search" @click="search">查询</Button>
                    <Button type="warning" icon="paper-airplane">委托定时任务</Button>
                </Row>
                <Spin size="large" fix v-if="spinShow"></Spin>

            </div>
            <div :class="tableData.table_display">
            <!--<div>-->
                <Row>
                    <Table border :height="520" :columns="tableData.columns1" :data="tableData.data1"></Table>
                </Row>
                <Row style="margin-top: 20px">
                    <Page
                            :total="tableData.totalData.length"
                            class="float-right"
                            show-total
                            show-elevator
                            @on-change="updateTableData"
                    ></Page>
                </Row>

                <div style="margin-top: 20px">
                    <Progress :percent="query_progress" :stroke-width="20" status="active"></Progress>
                </div>
                <div style="margin-top: 20px">
                    <Button type="success" icon="arrow-left-a" @click="back">返回</Button>
                    <Button type="primary" icon="android-download">保存查询结果</Button>
                </div>
            </div>
        </Card>
    </div>

</template>

<script>
    // import electron from 'electron';
    export default {
        name: 'select-keyword-cover',
        data () {
            return {
                hide: '',
                input_data_div_display: '', // 控制输入内容的 div 是否隐藏
                total_data_num: 0, // 数据总数
                chongfu_num: 0, // 重复数
                fugailv: 0, // 覆盖率
                pingtai_num: 0, // 平台数
                yichang_num: 0, // 异常数
                editor_content: '', // 编辑框输入的内容
                searchEngineList: [
                    // {
                    //     value: '1',
                    //     label: '百度'
                    // },
                    // {
                    //     value: '2',
                    //     label: '搜狗'
                    // },
                    // {
                    //     value: '3',
                    //     label: '360'
                    // },
                    {
                        value: '4',
                        label: '手机百度'
                    }
                    // {
                    //     value: '5',
                    //     label: '手机搜狗'
                    // },
                    // {
                    //     value: '6',
                    //     label: '手机360'
                    // },
                    // {
                    //     value: '7',
                    //     label: '神马'
                    // }
                ], // 搜索引擎列表
                searchEngineModel: [], // 选择的搜索引擎列表
                optionSettings: 'putong', // 选项设置
                rankList: [
                    {
                        value: '10',
                        label: '10'
                    },
                    {
                        value: '20',
                        label: '20'
                    },
                    {
                        value: '30',
                        label: '30'
                    },
                    {
                        value: '40',
                        label: '40'
                    },
                    {
                        value: '50',
                        label: '50'
                    },
                    {
                        value: '60',
                        label: '60'
                    },
                    {
                        value: '70',
                        label: '70'
                    },
                    {
                        value: '80',
                        label: '80'
                    },
                    {
                        value: '90',
                        label: '90'
                    },
                    {
                        value: '100',
                        label: '100'
                    },
                    {
                        value: '150',
                        label: '150'
                    },
                    {
                        value: '200',
                        label: '200'
                    },
                    {
                        value: '300',
                        label: '300'
                    }
                ], // 查询前多少名的列表
                rankModel: '10', // 选择的名次
                fugai_tiaojian: '', // 覆盖匹配条件

                // 表格中的数据
                tableData: {
                    table_display: 'hidden',
                    columns1: [
                        {
                            title: '序号',
                            key: 'index'
                        },
                        {
                            title: '关键词',
                            key: 'keyword'
                        },
                        {
                            title: '排名个数',
                            key: 'rank_num'
                        },
                        {
                            title: '排名情况',
                            key: 'rank_info',
                            render: (h, params) => {
                                if (params.row.rank_info === '') {
                                    // return h('Spin', '查询中...');
                                    return h(
                                        'span',
                                        {
                                            style: {
                                                color: 'red'
                                            }
                                        },
                                        '查询中...'
                                    );
                                } else {
                                    return h('span', params.row.rank_info);
                                }
                            }
                        },
                        {
                            title: '搜索引擎',
                            key: 'search_engine'
                            // render (h, params) {
                            //     console.log(params);
                            //     let _this = this;
                            //     console.log(this.searchEngineList);
                            //     let searchEngineIndex = params.row.search_engine;
                            //     for (let i = 0; i < _this.searchEngineList.length; i++) {
                            //         if (_this.searchEngineList[i].value === searchEngineIndex) {
                            //             return h('', _this.searchEngineList[i].label);
                            //         }
                            //     }
                            // }
                        }
                    ],
                    data1: [
                        // {
                        //     index: 1,
                        //     keyword: 'xxx',
                        //     rank_num: 10,
                        //     rank_info: 'fds',
                        //     search_engine: 'baidu'
                        // },
                    ],
                    totalData: [],
                    current_page: 1 // 当前第几页
                },
                spinShow: false,
                query_progress: 0, // 查询进度百分比
                currentKeywordsIndex: 0, // 用于判断当前查询到哪个id
                okNum: 0 // 查询完多少条数据
            };
        },
        components: {
            editor: require('vue2-ace-editor')
        },
        methods: {
            initEditor (editor) {
                require('brace/mode/html');
                require('brace/theme/chrome');
            },

            getNowDateTime () {
                let mydate = new Date();
                let year = mydate.getFullYear(); // 四位数字表示的年份
                let month = mydate.getMonth(); // 数字表示的月份,0-11, 0表示1月
                let date = mydate.getDate(); // 日期,1~31
                let hours = mydate.getHours(); // 时，0~23
                let minutes = mydate.getMinutes(); // 分,0~59
                let seconds = mydate.getSeconds(); // 秒,0~59
                let nowDateTime = year + '-' + (month + 1) + '-' + date + ' ' + hours + ':' + minutes + ':' + seconds; // 2017-12-28 20:53:53
                return nowDateTime;
            },

            selectKeywordRank () {
                if (this.currentKeywordsIndex === this.tableData.totalData.length) {
                    console.log('所有数据都已经跑完');
                    return true;
                }
                let eventName = Math.random().toString().split('.')[1];
                console.log('eventName --> 开始查询数据', eventName, this.getNowDateTime());
                let sendData = {
                    data: this.tableData.totalData[this.currentKeywordsIndex],
                    fugaiTiaoJian: this.fugai_tiaojian,
                    eventName: eventName,
                    currentKeywordsIndex: this.currentKeywordsIndex
                };
                this.currentKeywordsIndex += 1; // 当前查询id 自增1
                // for (let i = 0; i < this.tableData.data1.length; i++) {
                //     if (this.tableData.data1[i].index === this.current_keywords_id) {
                //         sendData.data = this.tableData.data1[i];
                //         this.current_keywords_id += 1; // 当前查询id 自增1
                //         break;
                //     }
                // }
                this.$electron.ipcRenderer.once(eventName, (event, arg) => {
                    console.log('arg -->', arg);
                    let rankList = [];
                    let rankNum = arg.length;
                    // let currentKeywordsIndex = arg.currentKeywordsIndex;
                    // [[3, "巴州五洲医院做包茎手术如何", 0, "-", "http://pktybr.ane.h6ow.cn/", "", ""], [3, "巴州五洲医院做包茎手术如何", "8", "-", "http://pktybr.ane.h6ow.cn/", "", ""]]
                    for (let i1 = 0; i1 < arg.length; i1++) {
                        if (arg.length > 1) {
                            if (arg[i1][2] !== 0) {
                                rankList.push(arg[i1][2]);
                            } else {
                                rankNum -= 1;
                            }
                        } else {
                            rankNum = 0;
                            rankList.push('-');
                        }
                    }
                    let rankInfo = rankList.join(',');

                    let index = arg[0][0] - 1;
                    this.tableData.totalData[index].rank_info = rankInfo;
                    this.tableData.totalData[index].rank_num = rankNum;
                    this.updateTableData(parseInt(index / 10) + 1, false);
                    this.okNum += 1;
                    // for (let i2 = 0; i2 < this.tableData.data1.length; i2++) {
                    //     if (this.tableData.data1[i2].index === arg[0][0]) {
                    //         this.tableData.data1[i2].rank_info = rankInfo;
                    //         this.tableData.data1[i2].rank_num = rankNum;
                    //     }
                    //
                    //     // 如果该任务有 rank_info 说明已经查完
                    //     if (this.tableData.data1[i2].rank_info) {
                    //         okNum += 1;
                    //     }
                    // }
                    this.query_progress = parseInt(this.okNum / this.tableData.totalData.length * 100);
                    console.log('this.query_progress -->', eventName, this.query_progress);
                    console.log('this.okNum -->', eventName, this.okNum);

                    this.selectKeywordRank();
                });

                // console.log('sendData -->', sendData);
                if (sendData.data !== null) {
                    this.$electron.ipcRenderer.send('SelectKeywordCover', sendData);
                }
            },

            // 更新表格数据
            updateTableData (page = 1, next = true) {
                if (!next && this.tableData.current_page !== page) {
                    // 什么也不干
                } else {
                    this.tableData.current_page = page;
                    let start = (page - 1) * 10;
                    let stop = start + 10;
                    this.tableData.data1 = this.tableData.totalData.slice(start, stop);
                }
            },

            // 查询按钮被点击
            search () {
                let _this = this;
                let flag = true;

                // 判断是否填写关键词
                if (!this.editor_content.trim()) {
                    flag = false;
                    this.$Message.warning('请输入关键词');
                }

                // 判断是否选择查询搜索引擎
                if (flag && this.searchEngineModel.length === 0) {
                    flag = false;
                    this.$Message.warning('请选择搜索引擎');
                }

                // 判断是否填写关键词
                if (flag && !this.fugai_tiaojian.trim()) {
                    flag = false;
                    this.$Message.warning('请输入覆盖条件');
                }

                if (flag) {
                    this.spinShow = true;
                    setTimeout(function () {
                        let keywordList = _this.editor_content.trim().split('\n');
                        let index = 1;

                        let searchEnginedict = {};
                        for (let i = 0; i < _this.searchEngineList.length; i++) {
                            let value = _this.searchEngineList[i].value;
                            searchEnginedict[value] = _this.searchEngineList[i].label;
                        }

                        // 生成表格数据
                        for (let i = 0; i < keywordList.length; i++) {
                            let keyword = keywordList[i];
                            for (let x = 0; x < _this.searchEngineModel.length; x++) {
                                let lineData = {
                                    index: index,
                                    keyword: keyword,
                                    rank_num: '',
                                    rank_info: '',
                                    search_engine: searchEnginedict[_this.searchEngineModel[x]]
                                };

                                _this.tableData.totalData.push(lineData);
                                index += 1;
                                // console.log('_this.tableData.totalDat -->', _this.tableData.totalData);
                                // console.log('_this.tableData.data1.length -->', _this.tableData.data1.length);
                            }
                        }

                        _this.updateTableData();

                        // 开始查询关键词覆盖
                        let dataLength = _this.tableData.totalData.length;
                        if (dataLength > 5) {
                            dataLength = 5;
                        }
                        for (let i = 0; i < dataLength; i++) {
                            _this.selectKeywordRank();
                        }
                        _this.input_data_div_display = 'hidden';
                        _this.tableData.table_display = '';
                        _this.spinShow = false;
                    }, 1000);
                }
            },
            // 点击返回
            back () {
                this.input_data_div_display = '';
                this.tableData.table_display = 'hidden';
            }

        },
        mounted () {

        },
        watch: {
            editor_content () {
                // 监听输入查询关键词发生变化则更新数据总数
                this.total_data_num = this.editor_content.split('\n').length;
            }
        }
    };
</script>
